<?php

	error_reporting(0);
	session_start();
	error_reporting(1);

	require_once "../PinSQL.obj" ;
	$pinSQL = new PinSQL();
	
	$type = $_POST['type'];
	require_once "Gallery_new.obj";
	include "setupGallery.php"; //creates a $gallery object which we can use for table names and other specifics

	// deal with the comments
	$itemID = $_POST["itemid"];
	
	$rating = $_POST["rating"];
	$visitor = $_POST["visitor"];
	
	$result = mysql_query("SELECT * FROM $gallery->dataTable WHERE id='$itemID'") or die(mysql_error());
	$totalstars = mysql_result($result, 0, "totalstars");
	$totalratings = mysql_result($result, 0, "totalratings");
	
	$totalstars += ($rating*2);
	$totalratings++;
  
	mysql_query("UPDATE $gallery->dataTable SET totalstars='$totalstars', totalratings='$totalratings' WHERE id='$itemID'")
	or die(mysql_error());
    
	// RSS
	if ( isset($_SESSION['username']) )
	{
		$user = $_SESSION['username'];	
	} else {
		$user = '[guest]';	
	}
     
	mysql_query("INSERT INTO activity
	(event_type, by_user, param_1, param_2, url_1)
	VALUES('new-$gallery->galleryItemName-rating', '$user', '$itemID', '$rating',
	'/common/gallery/portal_$gallery->galleryType.php?dest=$itemID') ")
	or die(mysql_error());
	
		// email notification
		$realname = $pinSQL->GetUserField($user, "firstname") . " " . $pinSQL->GetUserField($user, "lastname");
		if ($realname == " ")
			$realname = $user;
		$touser = $pinSQL->GetMediaField($gallery->dataTable, $itemID, "artist");
		$subject = "$realname rated your $gallery->galleryItemName \"" . $pinSQL->GetMediaField($gallery->dataTable, $itemID, "name") . "\" on The Pin Project...";
		$messageEmail = "$realname rated your $gallery->galleryItemName, \"" . $pinSQL->GetMediaField($gallery->dataTable, $itemID, "name") . ",\" as $rating/5. ";
		$sex = $pinSQL->GetUserdataField($user, "sex");
		switch ($rating)
		{
			case 5:	$messageEmail .= "Keep up the good work!"; break;
			case 4:	$messageEmail .= "Nice job!"; break;
			case 3:	$messageEmail .= "Not too bad."; break;
			case 2:	$messageEmail .= "Hmm.. better luck next time? Keep trying!"; break;
			case 1:	$messageEmail .= (($sex=="f")?"She":"He") . " is clearly suffering from delusions of bad taste.."; break;
		}
		$messageEmail .= "\n\n___________________________________"
		. "\nVisit the Pin Project: http://www.pinproject.com"
		. "\nYou are receiving this message because e-mail notifications are turned on. You can turn them off in your profile settings.";
		
		include "../../members/email_notify.php";
     
	$averagestars = round($totalstars / $totalratings / 2, 0);
     
	echo "$rating,$totalratings,$totalstars,$averagestars";
  
	mysql_close();

?>